package cn.time1024.time_app

import android.content.Intent
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.CheckBox
import androidx.appcompat.app.AppCompatActivity
import com.example.timeassistant.network.RegisterRequest
import com.example.timeassistant.network.ResponseEnvelope
import com.example.timeassistant.network.AppUserDto
import com.example.timeassistant.network.RetrofitClient
import com.example.timeassistant.network.TokenManager
import com.example.timeassistant.network.LoginApiRequest
import com.example.timeassistant.network.LoginApiData
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import cn.jpush.android.api.JPushInterface
import java.util.Locale
import android.util.Log

class LoginActivity : AppCompatActivity() {
    private val prefs by lazy { getSharedPreferences("auth_prefs", MODE_PRIVATE) }
    private lateinit var cbRememberAccount: CheckBox
    private lateinit var cbRememberPassword: CheckBox

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_login)

        val etUsername = findViewById<EditText>(R.id.etUsername)
        val etPassword = findViewById<EditText>(R.id.etPassword)
        val btnLogin = findViewById<Button>(R.id.btnLogin)
        val btnGoRegister = findViewById<Button>(R.id.btnGoRegister)
        val tvMessage = findViewById<TextView>(R.id.tvMessage)
        cbRememberAccount = findViewById(R.id.cbRememberAccount)
        cbRememberPassword = findViewById(R.id.cbRememberPassword)

        // 读取记住选项并按需自动填充与自动登录
        val rememberAccount = prefs.getBoolean("remember_account", false)
        val rememberPassword = prefs.getBoolean("remember_password", false)
        cbRememberAccount.isChecked = rememberAccount
        cbRememberPassword.isChecked = rememberPassword

        val savedAccount = prefs.getString("saved_account", "").orEmpty()
        val savedPassword = prefs.getString("saved_password", "").orEmpty()
        if (rememberAccount && savedAccount.isNotEmpty()) {
            etUsername.setText(savedAccount)
        }
        if (rememberPassword && savedPassword.isNotEmpty()) {
            etPassword.setText(savedPassword)
        }
        // 当两者都选择记住且均有值时，自动登录
        if (rememberAccount && rememberPassword && savedAccount.isNotEmpty() && savedPassword.isNotEmpty()) {
            tvMessage.text = "正在自动登录..."
            performLogin(savedAccount, savedPassword, tvMessage)
        }

        btnLogin.setOnClickListener {
            val account = etUsername.text?.toString()?.trim().orEmpty()
            val password = etPassword.text?.toString().orEmpty()
            tvMessage.text = ""
            performLogin(account, password, tvMessage)
        }

        btnGoRegister.setOnClickListener {
            startActivity(android.content.Intent(this, RegisterActivity::class.java))
        }
    }

    private fun performLogin(account: String, password: String, tvMessage: TextView) {
        // 使用后台统一登录接口 /loginApi
        val call = RetrofitClient.api.loginApi(LoginApiRequest(account = account, password = password, rememberMe = true))
        call.enqueue(object : Callback<ResponseEnvelope<LoginApiData>> {
            override fun onResponse(
                call: Call<ResponseEnvelope<LoginApiData>>, response: Response<ResponseEnvelope<LoginApiData>>
            ) {
                if (!response.isSuccessful) {
                    tvMessage.text = "登录失败：${response.code()}"
                    return
                }
                val body = response.body()
                val ok = (body?.success == true) || (body?.code == "00000")
                if (ok && body?.data?.token?.isNotBlank() == true) {
                    tvMessage.text = "登录成功"
                    // 保存记住选项
                    prefs.edit()
                        .putBoolean("remember_account", cbRememberAccount.isChecked)
                        .putBoolean("remember_password", cbRememberPassword.isChecked)
                        .apply()

                    // 保存当前登录账号（用于首页展示），按勾选保存账号/密码，并保存 token
                    val token = body.data.token!!
                    prefs.edit().apply {
                        putString("current_account", account)
                        if (cbRememberAccount.isChecked) {
                            putString("saved_account", account)
                        } else {
                            remove("saved_account")
                        }
                        if (cbRememberPassword.isChecked) {
                            putString("saved_password", password)
                        } else {
                            remove("saved_password")
                        }
                        putString("auth_token", token)
                    }.apply()
                    TokenManager.token = token

                    // ====== JPush: 设置别名与默认标签，并获取 RegistrationID ======
                    var rid: String? = null
                    try {
                        val userIdOrAccount = body.data.userId?.takeIf { !it.isNullOrBlank() } ?: account
                        val alias = ("u_" + userIdOrAccount!!.lowercase(Locale.getDefault())
                            .replace(Regex("[^a-z0-9_]+"), "_")).take(40)
                        val aliasSeq = 1001
                        val tagsSeq = 1002
                        val defaultTags = hashSetOf("android", "app", "prod")
                        JPushInterface.setAlias(applicationContext, aliasSeq, alias)
                        JPushInterface.setTags(applicationContext, tagsSeq, defaultTags)
                        rid = JPushInterface.getRegistrationID(applicationContext)
                        Log.d("JPush", "setAlias=${alias}, tags=${defaultTags}, rid=${rid}")
                    } catch (e: Throwable) {
                        Log.e("JPush", "设置别名/标签失败", e)
                    }

                    // 将 RegistrationID 与登录后返回的 userId 上报到 AppUser 登录接口，用于绑定设备
                    try {
                        val sysUserIdLong = body.data.userId?.toLongOrNull()
                        val req = RegisterRequest(
                            account = account,
                            password = password,
                            nickname = null,
                            registrationId = rid,
                            sysUserId = sysUserIdLong
                        )
                        RetrofitClient.api.appUserLogin(req).enqueue(object : Callback<ResponseEnvelope<AppUserDto>> {
                            override fun onResponse(
                                call: Call<ResponseEnvelope<AppUserDto>>, resp: Response<ResponseEnvelope<AppUserDto>>
                            ) {
                                if (!resp.isSuccessful) {
                                    Log.w("AppUserLogin", "上报 registrationId/sysUserId 失败：HTTP ${resp.code()}")
                                    return
                                }
                                val ok2 = resp.body()?.success == true || resp.body()?.code == "00000"
                                if (ok2) {
                                    Log.d("AppUserLogin", "registrationId/sysUserId 绑定成功")
                                } else {
                                    Log.w("AppUserLogin", "registrationId/sysUserId 绑定失败：${resp.body()?.message}")
                                }
                            }

                            override fun onFailure(call: Call<ResponseEnvelope<AppUserDto>>, t: Throwable) {
                                Log.e("AppUserLogin", "上报 registrationId/sysUserId 异常：${t.message}", t)
                            }
                        })
                    } catch (e: Throwable) {
                        Log.e("AppUserLogin", "调用 appUser/login 异常", e)
                    }

                    // 跳转到主页
                    startActivity(Intent(this@LoginActivity, MainActivity::class.java))
                    finish()
                } else {
                    tvMessage.text = body?.message ?: "登录失败"
                }
            }

            override fun onFailure(call: Call<ResponseEnvelope<LoginApiData>>, t: Throwable) {
                tvMessage.text = "网络错误：${t.message}"
            }
        })
    }
}